﻿using CandidateManager.Areas.Coach.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WI.CandidateManager.Business.Objects;
using WI.CandidateManager.Common.Data.Entities;

namespace CandidateManager.Areas.Coach.Controllers
{
	public class OccurrenceController : CandidateManager.Controllers.AutorizeBaseController
	{
		private OccurrenceBO occurrenceBO;

		public OccurrenceController()
			: base()
		{
			occurrenceBO = new OccurrenceBO();
		}

		[Authorize]
		public ActionResult Create(long subjectId, long groupId, long? occurrenceId = null)
		{
			OccurrenceModifyModel occurrenceModel = new OccurrenceModifyModel()
			{
				Occurrences = occurrenceBO.GetOccurrences(null, subjectId, groupId),
				Schedule = new ScheduleBO().GetSchedules(subjectId, groupId).Single()
			};
			occurrenceModel.Occurrence.Schedule = occurrenceModel.Schedule;
			if (occurrenceId.HasValue)
			{
				occurrenceModel.Occurrence = occurrenceBO.GetOccurrences(occurrenceId, null, null).Single();
			}
			return View(occurrenceModel);
		}

		[Authorize]
		[HttpPost]
		public ActionResult Create(OccurrenceModifyModel model)
		{
			OccurrenceModifyModel helpModel = new OccurrenceModifyModel();
			if (model.Occurrence.Id > 0)
			{
				helpModel.Occurrence = model.Occurrence;
				model.Occurrence = occurrenceBO.GetOccurrences(model.Occurrence.Id).Single();
				model.Occurrence.From = helpModel.Occurrence.From;
				model.Occurrence.To = helpModel.Occurrence.To;
			}
			model.Occurrence.Schedule = new ScheduleBO().GetSchedules(model.Schedule.SubjectId, model.Schedule.StudyGroupId).Single();
			if (occurrenceBO.SaveOccurence(model.Occurrence))
			{
				return RedirectToAction("Create", new { @subjectId = model.Occurrence.Schedule.SubjectId, @groupId = model.Occurrence.Schedule.StudyGroupId });
			}
			else
			{
				return RedirectToAction("Create");
			}
		}

		[Authorize]
		public ActionResult Delete(long occurrenceId)
		{
			var occurrence = occurrenceBO.GetOccurrences(occurrenceId).Single();
			if (occurrenceBO.DeleteOccurence(occurrenceId))
			{
				return RedirectToAction("Create", new { @subjectId = occurrence.Schedule.SubjectId, @groupId = occurrence.Schedule.StudyGroupId });
			}
			else
			{
				return RedirectToAction("Create");
			}
		}
	}
}
